package com.xzzz.irda.registry.service;

import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.common.base.util.thread.NamedThreadFactory;
import com.xzzz.irda.registry.RedisRegistryConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisServiceRegistry implements ServiceRegistry<RedisRegistration> {

    private StringRedisTemplate redisTemplate;

    private final ScheduledExecutorService registryTask = Executors.newScheduledThreadPool
            (1, new NamedThreadFactory("irda-register-task"));

    private String serviceInstanceStr;

    public RedisServiceRegistry(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void register(RedisRegistration registration) {
        if (StrUtil.isBlank(registration.getServiceId())) {
            return;
        }

        RedisServiceInstance serviceInstance = new RedisServiceInstance();
        serviceInstance.setServiceId(registration.getServiceId());
        serviceInstance.setHost(registration.getHost());
        serviceInstance.setPort(registration.getPort());
        serviceInstance.setSecure(false);
        serviceInstance.setMetadata(registration.getMetadata());
        if (serviceInstance.getMetadata() == null) {
            serviceInstance.setMetadata(new HashMap<>());
        }

        serviceInstanceStr = JsonUtil.toJson(serviceInstance);

        registryTask.scheduleAtFixedRate(() -> {
            redisTemplate.opsForValue().set(
                    RedisRegistryConstant.REDIS_SC_SERVICE + registration.getInstanceId(),
                    serviceInstanceStr,
                    15,
                    TimeUnit.SECONDS);
        }, 0,5, TimeUnit.SECONDS);

        log.info("[REGISTRY] 服务注册: {}", serviceInstanceStr);
    }

    @Override
    public void deregister(RedisRegistration registration) {
        if (StrUtil.isBlank(registration.getServiceId())) {
            return;
        }
        log.info("[REGISTRY] 服务注销: {}", JsonUtil.toJson(registration));
        redisTemplate.opsForHash().delete(RedisRegistryConstant.REDIS_SC_SERVICE, registration.getServiceId());
    }

    @Override
    public void close() {
//        log.warn("[REGISTRY] 简单注册不提供服务关闭功能");
    }

    @Override
    public void setStatus(RedisRegistration registration, String status) {
        log.info("设置状态");
    }

    @Override
    public Object getStatus(RedisRegistration registration) {
        log.info("获取状态");
        return "ok";
    }
}
